
package com.qf.cloud2204.coupons.controller;

import com.qf.cloud2204.coupons.entity.Coupon;
import com.qf.cloud2204.coupons.feignclient.MircoTokenClient;
import com.qf.cloud2204.coupons.service.ICouponService;
import io.lettuce.core.output.MapOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.ws.rs.PUT;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zxz
 * @since 2023-05-19
 */

@RestController
@RequestMapping("/coupons")
public class CouponController {
    @Autowired
    ICouponService couponService;
    @Autowired
    MircoTokenClient mircoTokenClient;


    //用feign调用MICROTOKEN服务的genToken接口
    @GetMapping("/genToken")
    public Map<String, Object> genToken(String number){
        // 调用微服务micro-token的 gentoken 接口
        HashMap<String, Object> map = mircoTokenClient.genToken(number);
        return map;
    }

    //抢券接口
    @PostMapping("/grab")
    public HashMap<String,Object> grab(String token,String batchId){
        HashMap<String, Object> verify = mircoTokenClient.verify(token);
        String number = (String) verify.get("number");
        HashMap<String, Object> map = new HashMap<>();
        if (number!=null&&!number.equals("")){
          boolean flag = couponService.grab(batchId,number);
          if (flag){
              map.put("code",1);
              map.put("msg","用户"+number+"抢券成功");
              return map;
          }
        }
        map.put("code",-1);
        map.put("msg","抢券失败");
        return map;
    }



    //批量创建优惠券接口
    @PostMapping("/add")
    public String createCoupons(BigDecimal amount,Integer count) {
        //调用createCoupons方法来生成优惠券
    String batchId = couponService.createCoupons(amount,count);
    if (batchId==null){
        throw new RuntimeException("生成优惠券失败");
    }
    return batchId;
    }

    //投放接口
    @PostMapping("/put")
    public String putCoupons(String batchId){

     boolean flag = couponService.putCoupons(batchId);
        if (flag){
            return "投放成功";
        }else {
            return "投放失败";
        }

    }







}

